<template>
	<view class="content">
		<view class="back" @click="goBack">
			<image class="img" :src="$imgUrl + '/login/back.png'" mode=""></image>
		</view>
		<view class="logo">
			<!--<image class="img" :src="$imgUrl + '/login/logo.png'" mode=""></image>-->
		</view>
		<view class="bgIcon">
			<image class="img" :src="$imgUrl + '/login/bg_icon.png'" mode=""></image>
		</view>
		<view class="formBox">
			<view class="welcome">
				<image class="img" :src="$imgUrl + '/login/welcome.png'" mode=""></image>
			</view>
			<form>
				<view class="uni-form-item uni-column">
					<view class="icon tenant"></view>
					<picker mode="selector" :range="tenants" range-key="name" @change="onTenantChange"
						:value="tenantIndex">
						<view class="uni-input" :style="{ color: '#FFC4C4' }">{{ selectedTenantName || '请选择租户' }}</view>
					</picker>
				</view>
				<view class="uni-form-item uni-column">
					<view class="icon phone"></view>
					<input class="uni-input" name="input" v-model="form.phone" placeholder="输入您的手机号" maxlength="11"
						placeholder-style="color:#FFC4C4;" type="number" />
				</view>
				<view class="uni-form-item uni-column">
					<view class="icon code"></view>
					<input class="uni-input" name="input" v-model="form.code" placeholder="输入您收到的验证码" maxlength="6"
						placeholder-style="color:#FFC4C4;" type="number" />
					<view class="send">
						<text v-show="showText" @click="handleGetCode">获取验证码</text>
						<text v-show="!showText">{{second}}&nbsp;S</text>
					</view>
				</view>
				<view class="tip">
					<checkbox-group @change="changeCheck" class="inlineBlock">
						<!-- #ifdef MP-WEIXIN -->
						<checkbox :value="true" style="scale: 0.7;" />
						<!-- #endif -->
						<!-- #ifndef MP-WEIXIN -->
						<checkbox :value="true" color="#fff" />
						<!-- #endif -->
					</checkbox-group>
					我已详细阅读并同意<text class="link"
						@click="$Foundation.goTo('/pages/personal/aboutUs/agreement')">《用户隐私政策》</text>
				</view>
				<view class="uni-btn-v">
					<button class="btn" @click="login">登 录</button>
					<!-- #ifdef MP-WEIXIN -->
					<!-- <button type="default" class="wxchat-btn" open-type="getPhoneNumber"
                        @getphonenumber="wxChatLogin">快捷登录</button> -->
					<!-- #endif -->
					<!-- #ifdef APP-PLUS -->
					<!--<view class="oneLogin center" v-if="showOneLogin" @click="fastLogin">手机号一键登录</view>-->
					<!-- #endif -->
				</view>
			</form>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<view class="refuse" @click="goBack">暂不登录</view>
		<!-- #endif -->
	</view>
</template>

<script lang="ts" setup>
	import { ref, reactive, onMounted } from 'vue'
	import { getCode, smsLogin, phoneLogin, getPhoneCode, getTenantData } from '@/common/API/login'
	import { getOpenId, getPhone } from '@/common/API/wxchat'
	import { checkPhone } from '@/utils/Foundation.js'
	import { useStore } from 'vuex'
	import { onLoad } from "@dcloudio/uni-app"

	const store = useStore()

	const radioFlag = ref(false)
	const form = reactive({
		phone: '',
		code: '',
		tenantId: '' // 添加租户编号字段
	})
	const selectedTenantName = ref(''); // 选中的租户名称
	const tenantIndex = ref(-1); // 选中的租户索引
	const tenants = ref([]); // 租户列表
	const second = ref(60)
	const showText = ref(true)
	const isCheck = ref(false)
	const recommendId = ref()
	const showOneLogin = ref(true)

	onMounted(async () => {
		const params = {
			pageNo: 1,
			pageSize: 100
		};
		try {
			const response = await getTenantData(params);
			console.log(response);
			if (response ) {
				tenants.value = response.list.map(item => ({
					name: item.name,
					id: item.id 
				}));
				if (tenants.value.length > 0) {
					selectedTenantName.value = tenants.value[0].name; 
					form.tenantId = tenants.value[0].id; 
				}
			}
			console.log('Tenants:', tenants.value);
		} catch (error) {
			console.error(error); // 处理错误
		}
	});
	onLoad(() => {
		if (uni.getStorageSync('recommendId')) {
			recommendId.value = uni.getStorageSync('recommendId');
		}
		// #ifdef APP-PLUS
		// uni.preLogin({
		//     provider: 'univerify',
		//     success() {  //预登录成功
		//         showOneLogin.value = true;
		//     },
		//     fail(res) {  // 预登录失败
		//         showOneLogin.value = false;
		//         console.log(res.errMsg);
		//     }
		// });
		// #endif
	});

	const handleGetCode = () => {
		if (!form.phone) {
			uni.showToast({
				title: '请输入您的手机号',
				icon: 'none',
			});
			return false;
		} else if (!checkPhone(form.phone)) {
			uni.showToast({
				title: '请输入正确的手机号',
				icon: 'none',
			});
			return false;
		} else {
			sendVerifyCode();
		}
	};

	const onTenantChange = (e) => {
		const index = e.detail.value;
		const selectedTenant = tenants.value[index];
		selectedTenantName.value = selectedTenant.name;
		form.tenantId = selectedTenant.id; // 将租户编号绑定到表单
		tenantIndex.value = index;
	};

	const sendVerifyCode = async () => {
		let data = {
			mobile: form.phone,
			scene: 1
		};
		uni.showLoading();
		let res = await getCode(data);
		uni.hideLoading();
		showText.value = false;
		var interval = setInterval(() => {
			--second.value;
		}, 1000);
		setTimeout(() => {
			clearInterval(interval);
			showText.value = true;
			second.value = 60;
		}, 60000);
	};

	const changeCheck = (e) => {
		isCheck.value = e.detail.value[0];
	};

	const login = async () => {
		store.dispatch('logOut');
		uni.setStorageSync('tenantId', form.tenantId);
		if (!form.phone) {
			uni.showToast({
				title: '请输入您的手机号',
				icon: 'none',
			});
			return false;
		} else if (!checkPhone(form.phone)) {
			uni.showToast({
				title: '请输入正确的手机号',
				icon: 'none',
			});
			return false;
		} else if (!form.code) {
			uni.showToast({
				title: '请输入验证码',
				icon: 'none',
			});
			return false;
		} else if (!form.tenantId) {
			uni.showToast({
				title: '请选择租户',
				icon: 'none',
			});
			return false;
		} else if (!isCheck.value) {
			uni.showToast({
				title: '请详细阅读《用户隐私政策》',
				icon: 'none',
			});
			return false;
		} else {
			uni.showLoading({
				title: '登录中...'
			});
			let data = {
				mobile: form.phone,
				code: form.code,
				recommendId: recommendId.value,
				tenantId: form.tenantId, // 添加租户编号
				// 新增租户编码参数
				tenantCode: tenants.value.find(t => t.id === form.tenantId)?.code 
			};
			let res = await smsLogin(data);
			uni.hideLoading();
			res.userPhone = form.phone;
			res.accessToken = 'Bearer ' + res.accessToken;
			uni.setStorageSync('recommendId', '');
			store.dispatch('setLoginData', res);
			let pages = getCurrentPages();
			let beforePage = pages.length > 1 ? pages[pages.length - 2].route : '';
			if (beforePage) {
				uni.navigateBack();
			} else {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}
		}
	};

	const goBack = () => {
		uni.switchTab({
			url: '/pages/index/index'
		});
	};

	// #ifdef MP-WEIXIN
	const wxChatLogin = async (e) => { //微信授权登录
		let openId = uni.getStorageSync("openId");
		uni.setStorageSync('tenantId', form.tenantId);
		if (!openId) {
			// 获取openId
			uni.login({
				provider: 'weixin',
				success: (res) => {
					let data = {
						appId: config.NewWxChatAppId,
						code: res.code
					};
					getOpenId(data).then((openIdstr) => {
						store.dispatch("SET_OPENID", openIdstr);
						console.log('openIdstr:' + openIdstr);
					});
				}
			});
		}
		//获取手机号
		let p = {
			appId: config.NewWxChatAppId,
			code: e.detail.code,
			recommendId: recommendId.value
		};
		let loginData = await getPhone(p);
		loginData.accessToken = 'Bearer ' + loginData.accessToken;
		store.dispatch('setLoginData', loginData);
		uni.switchTab({
			url: '/pages/index/index'
		});
	};
	// #endif

	const fastLoading = ref(false);
	// #ifdef APP-PLUS
	const fastLogin = () => {
		if (!fastLoading.value) {
			fastLoading.value = true;
			uni.setStorageSync('tenantId', form.tenantId);
			uni.login({
				provider: 'univerify',
				univerifyStyle: {
					"icon": {
						"path": 'static/images/logo.png'
					},
					"authButton": {
						"normalColor": "#FD9618",
						"highlightColor": "#d37605"
					},
					"privacyTerms": {
						"termsColor": "#FD9618"
					},
					"otherLoginButton": {
						"visible": "false"
					}
				},
				success(result) { // 登录成功
					fastLoading.value = false;
					if (result.errMsg == 'login:ok') {
						//执行云函数
						uniCloud.callFunction({
							name: 'getPhoneNumber',
							data: {
								access_token: result.authResult['access_token'],
								openid: result.authResult['openid']
							}
						}).then(async res => {
							//关闭弹框事件
							uni.closeAuthView();
							if (res.result['code'] == 0) {
								//获取的手机号
								uni.showLoading({
									title: '登录中...'
								});
								let phoneNumber = res.result.data.phoneNumber;
								let code = await getPhoneCode();
								console.log('code:' + code);
								let loginInfo = await phoneLogin(phoneNumber, code);
								console.log('loginInfo:' + loginInfo);
								uni.hideLoading();
								loginInfo.userPhone = phoneNumber;
								loginInfo.accessToken = 'Bearer ' + loginInfo.accessToken;
								store.dispatch('setLoginData', loginInfo);
								uni.switchTab({
									url: '/pages/index/index'
								});
							} else {
								uni.showToast({
									icon: 'none',
									title: '授权失败~'
								});
							}
							//if end
						}).catch(msg => {
							//关闭弹框事件
							uni.closeAuthView();
							console.error(msg);
						});
					} else {
						//关闭弹框事件
						uni.closeAuthView();
					}
				},
				fail(res) {  // 登录失败
					fastLoading.value = false;
					console.log('登录失败:' + JSON.stringify(res));
					if (res['code'] != 30003) {
						uni.showToast({
							icon: 'none',
							title: res['errMsg']
						});
					}
				}
			});
		}
	};
	// #endif
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		height: 100vh;
		padding: var(--status-bar-height) 44rpx 0;
		background: linear-gradient(#FCD266, #FF536B);
		position: relative;

		.back {
			width: 48rpx;
			height: 48rpx;
			color: #fff;
			position: fixed;
			top: calc(30rpx + var(--status-bar-height));
			line-height: 48rpx;
		}

		.logo {
			width: 156rpx;
			height: 60rpx;
			margin: 150rpx 0 0 22rpx;
		}

		.bgIcon {
			width: 612rpx;
			height: 538rpx;
			position: absolute;
			top: 160rpx;
			right: 4rpx;
		}

		.welcome {
			width: 269rpx;
			height: 114rpx;
			margin: 0 0 80rpx 20rpx;
		}

		.formBox {
			margin: 380rpx 0 0;
			padding: 0 42rpx;
			/* #ifdef MP-WEIXIN */
			margin: 300rpx 0 0;

			/* #endif */
			.uni-form-item {
				height: 84rpx;
				line-height: 84rpx;
				background: #FFFFFF;
				box-shadow: 2rpx 2rpx 0px 2rpx rgba(175, 8, 16, 0.66);
				border-radius: 237rpx;
				margin: 0 0 48rpx;
				padding: 0 32rpx 0 44rpx;
				display: flex;
				align-items: center;

				.icon {
					width: 39rpx;
					height: 47rpx;
					margin: 0 18rpx 0 0;

					&.tenant {
						background: url('#{$imgUrl}/login/phone.png') no-repeat;
						background-size: 100% 100%;
					}

					&.phone {
						background: url('#{$imgUrl}/login/phone.png') no-repeat;
						background-size: 100% 100%;
					}

					&.code {
						background: url('#{$imgUrl}/login/password.png') no-repeat;
						background-size: 100% 100%;
					}
				}

				.uni-input {
					font-size: 26rpx;
					flex: 1;
					color: #FFC4C4; // 可以调整文字颜色
				}

				.send {
					color: #FF5C6B;
					font-weight: 500;
				}
			}

			.tip {
				padding: 12rpx 0 0;
				margin: 0 0 58rpx;
				color: #fff;
				font-size: 24rpx;

				::v-deep.uni-checkbox-input {
					width: 24rpx;
					height: 24rpx;
					background: none;
					color: #fff !important;
					border-color: #fff;
				}

				.link {
					display: inline-block;
					font-weight: bold;
				}
			}

			.uni-btn-v {
				.btn {
					width: 212rpx;
					height: 64rpx;
					line-height: 62rpx;
					color: #fff;
					background: #FF5C6B;
					border-radius: 14rpx;
					border: 2rpx solid #FFFFFF;

					&::after {
						display: none;
					}
				}

				.oneLogin {
					color: #fff;
					margin-top: 26rpx;
				}

				.wxchat-btn {
					background: transparent;
					border: 0;
					color: #fff;
					margin-top: 26rpx;
					font-size: 28rpx;
				}

				.wxchat-btn::after {
					display: none;
				}
			}
		}

		.refuse {
			position: fixed;
			color: #fff;
			text-align: center;
			bottom: 50rpx;
			left: 0;
			right: 0;
			margin: 0 auto;
		}
	}
</style>